# database_context.py
import threading
from typing import Optional

import sqlalchemy as sa
from sqlalchemy.orm import Session, sessionmaker, scoped_session
from sqlalchemy.pool import QueuePool

from .database_config import DatabaseConfig


class DatabaseContext:
    """数据库上下文管理器，提供线程安全的数据库会话访问"""
    _instance = None
    _lock = threading.Lock()
    _engine = None
    _session_factory = None
    _config: Optional[DatabaseConfig] = None
    
    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
        return cls._instance
    
    @classmethod
    def initialize(cls, config: Optional[DatabaseConfig] = None):
        """初始化数据库上下文"""
        if cls._engine is not None:
            return
            
        with cls._lock:
            if cls._engine is not None:
                return
                
            cls._config = config or DatabaseConfig()
            
            # 创建引擎
            cls._engine = sa.create_engine(
                cls._config.connection_string,
                poolclass=QueuePool,
                pool_size=cls._config.pool_size,
                max_overflow=cls._config.max_overflow,
                pool_timeout=cls._config.pool_timeout,
                pool_recycle=cls._config.pool_recycle
            )
            
            # 创建session工厂
            cls._session_factory = sessionmaker(bind=cls._engine)
            cls._scoped_session = scoped_session(cls._session_factory)


    @classmethod
    def get_session(cls) -> Session:

        """
        提供一个会话上下文管理器，确保会话在使用后被正确关闭

        """
        if cls._session_factory is None:
            cls.initialize()

        return cls._scoped_session()


       
    
    